Bite 341. Pydantic part II
Login and get codingIn order to measure daily food intake as a user our current
Foodmodel is not enough. We also needUserandFoodEntrymodels, so let's create them!In database-speak,
FoodEntryis a many-to-many relation betweenUserandFood. Users would add many foods and foods will be added by many users.For this learning path, we'll work with these Pydantic models in memory to keep things simpler. In the SQLModel learning path we'll use a database.
Create the
UserandFoodEntrymodels based on what you learned in the second FastAPI Bite in this series.Required attributes and their types:
User
-
id-> int
-username->str
-password->str(needed for authentication later)* For
passwordoverride the constructor (__init__.py) to hash the password upon creation of the module. You can use the providedget_password_hash()function for this.FoodEntry
-
id->int(what in a DB would be the primary key)
-user->User(here we see that Pydantic models can be nested)
-food->Food(from previous Bite and provided in the template)
-date_added->datetime(defaults todatetime.now())
-number_servings->float(fitness nerds can be quite exact about this)* Additionally add a property to calculate the total calories of a food entry (
number_servings * food.kcal_per_serving) and call ittotal_calories.Good luck and in the next Bite we'll expand our API to work with these new objects.
131 out of 137 users completed this Bite.
Will you be the 132nd person to crack this Bite?
Resolution time: ~56 min. (avg. submissions of 5-240 min.)
Our community rates this Bite 5.0 on a 1-10 difficulty scale.
» Up for a challenge? 💪